using System.Web.UI.HtmlControls;
using EPiServer.Core;

namespace EPiServer.Labs.MobilePack.Site.Units
{
    [DynamicContent.DynamicContentPlugIn(DisplayName = "[MobilePack] Button", ViewUrl = "~/modules/MobilePack/Units/Link.ascx", SortIndex=42000)]
    public partial class Link : EPiServer.UserControlBase
    {
        public string LinkText { get; set; }
        public PageReference InternalLink { get; set; }
        public string ExternalUrl { get; set; }
        public bool Dialog { get; set; }
        public bool InlineButton { get; set; }

        protected bool IsExternal
        {
            get
            {
                if (InternalLink == null) return true;
                if (InternalLink == PageReference.EmptyReference) return true;
                return !MobileBase.IsMobilePage(InternalLink);
            }
        }

        protected string LinkUrl
        {
            get
            {
                return (string.IsNullOrEmpty(ExternalUrl)) ? DataFactory.Instance.GetPage(InternalLink).LinkURL : ExternalUrl;
            }
        }

        protected string Text
        {
            get
            {
                return (string.IsNullOrEmpty(LinkText)) ? DataFactory.Instance.GetPage(InternalLink).PageName : LinkText;
            }
        }

        protected override void OnLoad(System.EventArgs e)
        {
            base.OnLoad(e);

            Controls.Add(RenderLink());
        }

        protected HtmlAnchor RenderLink()
        {
            var link = new HtmlAnchor();

            link.HRef = this.LinkUrl;
            link.Attributes["class"] = "mobileLink";
            link.Attributes["data-role"] = "button";

            if (this.Dialog)
            {
                link.Attributes["data-rel"] = "dialog";
            }

            if (this.IsExternal)
            {
                link.Attributes["rel"] = "external";
            }

            if (this.InlineButton)
            {
                link.Attributes["data-inline"] = "true";
            }

            link.InnerText = this.Text;

            return link;
        }
    }
}